package com.rockymew.core.mybatis.paging.dialect;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import com.rockymew.core.mybatis.paging.PageInfo;
import com.rockymew.core.mybatis.paging.utils.SqlUtil;

public class MySqlPageSqlSourceWapper extends PageSqlSourceWapper{

    public MySqlPageSqlSourceWapper(SqlSource sqlSource, PageInfo page) {
        super(sqlSource, page);
    }

    @Override
    public BoundSql getPageBoundSql(Object parameterObject) {
        BoundSql boundSql = getSqlSrouce().getBoundSql(parameterObject);
        MetaObject moBoundSql = SystemMetaObject.forObject(boundSql);
        String sql = boundSql.getSql( );

        StringBuilder pageSql = new StringBuilder(100);
        String beginrow = String.valueOf( (this.page.getPageNumber() - 1) * this.page.getPageSize());
        pageSql.append(sql);
        pageSql.append(" limit " + beginrow + "," + this.page.getPageSize() + " ");

        moBoundSql.setValue("sql", pageSql.toString());
        return boundSql;
    }

    @Override
    public BoundSql getCountBoundSql(Object parameterObject) {
        BoundSql boundSql = getSqlSrouce().getBoundSql(parameterObject);
        MetaObject moBoundSql = SystemMetaObject.forObject(boundSql);
        String sql = boundSql.getSql( );

        String countSql = SqlUtil.sqlToCountSql(sql);

        moBoundSql.setValue("sql", countSql);
        return boundSql;
    }

}
